package com.ruoyi.OnePipe;

import com.ruoyi.common.utils.http.HttpUtils;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.time.Instant;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatter;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;

public class SmsUtils {

    private static final String apiKey = "oAhJFOhciNOTz2qRSFRzMdSxjKBBGM2E";
    private static final String apiSecret = "FXhdHWXhFt6YFPqbLAlTE5YyEPyiN1tSjraJ";
    private static final String signId = "SS_gbLMSjB701";
    private static final String templateId = "ST_Q0L9Q0STPB";


    private static final String ALGORITHM = "HmacSHA256";

    private static String bytesToHex(byte[] hash) {
        StringBuilder hexString = new StringBuilder(2 * hash.length);
        for (int i = 0; i < hash.length; i++) {
            String hex = Integer.toHexString(0xff & hash[i]);
            if (hex.length() == 1) {
                hexString.append('0');
            }
            hexString.append(hex);
        }
        return hexString.toString();
    }

    public static String signature(String content, String secretKey) throws NoSuchAlgorithmException, InvalidKeyException {
        SecretKeySpec signingKey = new SecretKeySpec(secretKey.getBytes(StandardCharsets.UTF_8), ALGORITHM);
        Mac mac = Mac.getInstance(ALGORITHM);
        mac.init(signingKey);
        byte[] bytes = mac.doFinal(content.getBytes(StandardCharsets.UTF_8));
        return bytesToHex(bytes);
    }

    public static String hashPayload(String payload) throws NoSuchAlgorithmException {
        MessageDigest digest = MessageDigest.getInstance("SHA-256");
        byte[] encodedhash = digest.digest(payload.getBytes(StandardCharsets.UTF_8));
        return bytesToHex(encodedhash);
    }

    public static String currentDateTime() {
        String pattern = "yyyyMMdd'T'HHmmss'Z'";
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(pattern).withZone(ZoneId.of("UTC"));
        Instant instant = Instant.now();
        return dateTimeFormatter.format(instant);
    }

//    public static void main(String[] args) throws Exception {
//        String payload = "{\"to\": \"+23408050995364\", \"sign_id\": \"" + signId + "\", \"template_id\": \"" + templateId + "\", \"template_params\": {\"code\": \"1111\"}}";
//        System.err.print("payload:");
//        System.out.println(payload);
//        String hashedPayload = hashPayload(payload);
//        System.err.print("hashedPayload:");
//        System.out.println(hashedPayload);
//        String date = currentDateTime();
//        System.err.print("date:");
//        System.out.println(date);
//        String content = date + "\n" + hashedPayload;
//        System.err.print("content:");
//        System.out.println(content);
//        String signature = signature(content, apiSecret);
//        System.err.print("signature:");
//        System.out.println(signature);
//        String authorization = apiKey + ':' + date + ':' + signature;
//        System.err.print("authorization:");
//        System.out.println(authorization);
//
////        Map<String,String> map = new HashMap<>();
////        map.put("Authorization",authorization);
////
////        HttpUtils.sendPost("https://sms.cloudmatch.ai/v1/send-sms",payload,map);
//    }

    public static void main(String[] args) throws Exception {
        String appId ="10001";
        String apiKey ="xxxxx";
        long timestamp =1638878007500l;//13位的当前时间戳
        String param = "appId="+appId + "&apiKey="+apiKey+"&timestamp="+timestamp;
        String sign = encryptBASE64(param.getBytes());
        System.out.println("sign :" + sign);
        System.out.println("param :" +new String(decryptBASE64(sign)));
//        log.info("sign :" + sign);
//        log.info("param :" +new String(decryptBASE64(sign)));
    }

    /**
     * BASE64解密
     * @throws Exception
     */
    public static byte[] decryptBASE64(String key) throws Exception {
        return (new BASE64Decoder()).decodeBuffer(key);
    }

    /**
     * BASE64加密
     */
    public static String encryptBASE64(byte[] key) throws Exception {
        return (new BASE64Encoder()).encodeBuffer(key);
    }

}
